var G_windowTitle;
var form;
var G_id;
var zTree;
var G_pId = null;
$(document).ready(function () {
  initLayui();
  initTable();
  initMenuTree();
});

function initLayui() {
  layui.use(['form'], function () {
    form = layui.form;

    form.on('submit(filter)', function (data) {
      initTable();
      return false;
    });

    form.on('submit(save)', function (data) {
      var params = {
        id: G_windowTitle == '新增' ? null : G_id,
        name: data.field.name,
        path: data.field.path,
        icon: data.field.icon,
        pId: G_windowTitle == '新增' ? G_pId : data.field.pId,
        seqId: data.field.seqId,
      };
      save(params);
      return false;
    });
  });
}

// 新增编辑弹窗
function showWindow(title, res) {
  if (G_pId == null && title == '新增') {
    layer.msg('请先从左侧树上选中一个节点！');
  } else {
    layer.open({
      type: 1,
      title: title,
      skin: 'default-class',
      area: ['4.5rem', 'auto'],
      // shade: false,
      move: false,
      closeBtn: 2,
      id: 1, //设置该值后，不管是什么类型的层，都只允许同时弹出一个。
      content: `<form class="layui-form" lay-filter="saveForm" style="margin: .3rem;">
                <div class="layui-form-item">
                  <label class="layui-form-label">菜单名称</label>
                  <div class="layui-input-block">
                    <input type="text" name="name" autocomplete="off" class="layui-input" lay-verify="required">
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">菜单路径</label>
                  <div class="layui-input-block">
                    <input type="text" name="path" autocomplete="off" class="layui-input" lay-verify="required">
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">菜单图标</label>
                  <div class="layui-input-block">
                    <input type="text" name="icon" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <input type="hidden" name="pId" autocomplete="off" class="layui-input">
                <div class="layui-form-item">
                  <label class="layui-form-label">排序</label>
                  <div class="layui-input-block">
                    <input type="text" name="seqId" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-form-item form-btn" style="text-align:center">
                  <div class="layui-input-block" style="margin-left: 0;">
                    <button class="layui-btn" lay-submit lay-filter="save">保存</button>
                  </div>
                </div>
              </form>`, //这里content是一个普通的String
      success: function (layero, index) {
        G_windowTitle = title;
        form.render();
        if (title == '编辑') {
          G_id = res.id;
          //给表单赋值
          form.val('saveForm', {
            name: res.name,
            path: res.path,
            icon: res.icon,
            seqId: res.seqId,
            pId: res.pId,
          });
        }
      },
    });
  }
}

// 保存表单
function save(data) {
  AjaxRequest('/menu/save', callBack, data, 'post');

  function callBack(result) {
    if (result.status == 200) {
      layer.msg('保存成功！');
      initTable();
      initMenuTree();
      layer.closeAll();
    } else {
      layer.msg('保存失败！');
    }
  }
}

function initTable() {
  layui.use('table', function () {
    var table = layui.table;
    var height = $('.search-content').innerHeight() - 20;

    //第一个实例
    table.render({
      title: '',
      height: height,
      text: {
        none: '暂无数据',
      },
      elem: '#table',
      skin: 'nob',
      headers: {
        SessionId: JSON.parse(localStorage.getItem('userInfo')).sessionId,
      },
      url: ajaxPrefix() + '/menu/list',
      where: {
        pId: G_pId,
      },
      parseData: function (res) {
        //res 即为原始返回的数据
        return {
          code: res.status == 200 ? 0 : 1, //解析接口状态
          msg: res.message, //解析提示文本
          count: res.result?res.result.total:0, //解析数据长度
          data: res.result?res.result.data:[], //解析数据列表
        };
      },
      request: {
        pageName: 'pageNum', //页码的参数名称，默认：page
        limitName: 'pageSize', //每页数据量的参数名，默认：limit
      },
      page: {
        //开启分页
        limit: 10,
      },
      cols: [
        [
          //表头
          {
            field: 'name',
            title: '菜单名称',
            align: 'center',
          },
          {
            field: 'path',
            title: '菜单路径',
            align: 'center',
          },
          {
            field: 'seqId',
            title: '排序',
            align: 'center',
          },
          {
            field: '',
            title: '操作',
            align: 'center',
            width: 200,
            templet: function (d) {
              let res = JSON.stringify(d);
              return `<div class="table-tool">
                        <div onclick='showWindow("编辑",${res})'>
                          <img src="../static/img/edit.png">编辑
                        </div>
                        <div onclick='showDelWindow(${res})'>
                          <img src="../static/img/delete.png">删除
                        </div>
                      </div>`;
            },
          },
        ],
      ],
    });
  });
}

function initMenuTree() {
  AjaxRequest('/menu/tree', callBack);

  function callBack(result) {
    var zNodes = [
      {
        id: '',
        name: '全部',
        pId: '',
        path: '',
        icon: '',
      },
    ];
    zNodes = zNodes.concat(result.result);
    $.each(zNodes, function (i, val) {
      val.icon = '';
    });
    var setting = {
      data: {
        simpleData: {
          enable: true,
        },
      },
      callback: {
        onClick: onClick,
      },
    };
    zTree = $.fn.zTree.init($('#menu-tree'), setting, zNodes);

    // 获取第一个节点
    var firstNode = zTree.getNodes()[0];

    // 展开第一个节点
    zTree.expandNode(firstNode, true, false, false);

    function onClick(event, treeId, treeNode, clickFlag) {
      G_pId = treeNode.id;
      initTable();
    }
  }
}

function showDelWindow(res) {
  layer.confirm(
    '确认是否删除?',
    {
      btn: ['确认', '取消'], //按钮
    },
    function () {
      AjaxRequest('/menu/delete?id=' + res.id, callBack);

      function callBack(result) {
        if (result.status == 200) {
          layer.msg('删除成功!');
          initTable();
          initMenuTree();
          layer.closeAll();
        }
      }
    }
  );
}
